package com.itheima.health.service.impl;


import com.github.pagehelper.Page;
import com.itheima.health.dao.*;
import com.itheima.health.pojo.*;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

@DubboService
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public User findByUserName(String username) {
        log.info("用户登录-根据用户名查询用户：{}",username);
        //创建一个用户对象
        User user = new User();
        //传入用户名
        user.setUsername(username);
        //调用查询一个用户的方法 根据用户对象里的用户名查询用户
        User selectOne = userMapper.selectOne(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        //通过中间表得到所有role的id
        List<UserRole> roles = userRoleService.select(userRole);
        //遍历role的id通过id查询role的数据
        for (UserRole roleId : roles) {
            //通过id查询role的数据
            Role role = roleService.selectByPrimaryKey(roleId.getRoleId());
            //获取user中的set roles 进行赋值
            Set<Role> roleSet = selectOne.getRoles();
            //根据roleid查询 创建中间表对象
            RolePermission rolePermission = new RolePermission();
            //根据传入roleId
            rolePermission.setRoleId(role.getId());
            //根据roleId查询permissionId
            List<RolePermission> rolePermissions = rolePermissionMapper.select(rolePermission);
            //遍历permissionId
            for (RolePermission permissionId : rolePermissions) {
                //根据id查询permission数据
                Permission permission = permissionMapper.selectByPrimaryKey(permissionId.getPermissionId());
                //获取role中的setPermission
                Set<Permission> permissionSet = role.getPermissions();
                permissionSet.add(permission);
                role.setPermissions(permissionSet);
            }
            //将得到的role数据赋值进set集合中
            roleSet.add(role);
            selectOne.setRoles(roleSet);
        }
        log.info("用户登录-根据用户名查询用户结果：{}",selectOne);
        return selectOne;
    }
}
